<template>
    <section id="todo">
        <input
                type="text"
                placeholder="接下来要做什么？"
                @keypress.enter="addTodo"
        >
        <item
                v-for="todo in filteredTodo"
                :todo="todo"
                :key="todo.id"
                @del="delTodo"
        ></item>
        <tabs
                :todos="filteredTodo"
                :filter="filter"
                @toggle="toggleFilter"
                @clear="clearCompleted"
        ></tabs>
    </section>
</template>

<script>
    // import item from 'item.vue'  注意！
    import Item from "./item.vue";
    import Tabs from "./tabs.vue"

    export default {
        name: "todo",
        components: {
            Item,
            Tabs
        },
        data(){
          return{
              id: 0,
              filter: 'all',
              todos:[
                  {
                      id: 0,
                      content: '今天天气晴朗！',
                      completed: false
                  },
                  // {
                  //     id: 1,
                  //     content: '疫情期间在家待着！',
                  //     completed: false
                  // },
              ]
          }
        },
        computed: {
            filteredTodo() {
                if (this.filter === 'all') {
                    return this.todos
                } else if (this.filter === 'completed') {
                    return this.todos.filter(todo => todo.completed)
                }else {
                    return this.todos.filter(todo => ! todo.completed)
                }
            }
        },
        methods: {
            addTodo(event){
                let content = event.target.value.trim()
                if(content){
                    this.todos.push({
                        id: ++ this.id,
                        content: content,
                        completed: false
                    })
                    event.target.value = ''
                }else {
                    alert('输入不能为空！')
                }
            },
            delTodo(i){
                let index = this.todos.findIndex(todo => todo.id === i)
                this.todos.splice(index,1)
            },
            toggleFilter(state){
                this.filter = state
            },
            clearCompleted(){
                this.todos = this.todos.filter(todo => !todo.completed)
            }
        },
    }
</script>

<style lang="stylus" scoped>
    #todo
        width 600px
        background white
        padding 0 15px
        margin 0 auto
        input
            margin-left 30px
            margin-top 20px
            font-size 24px
            border none
            outline none
</style>